第12 屆iT邦幫忙鐵人賽系列文章 (Day5)
我想 Line 豐富的貼圖,應該是很多人喜歡用它來做 Chatbot 的一個原因吧
接續上一篇,我們試著在歡迎詞後,傳送一個禮貌又不尷尬的貼圖
我們接續前一篇 LineReplyMessageUtility 這個類別再實作一個回覆貼圖的method
public async Task ReplyStickerMessageAsync(string replyToken, string packageId, string stickerId)
{
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), $"{lineMessageApiBaseUrl}"))
{
request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {accessToken}");
LineMessageReq req = new LineMessageReq();
req.ReplyToken = replyToken;
req.Messages.Add(new StickerMessage()
{
PackageId = packageId,
StickerId = stickerId
});
var postJson = JsonConvert.SerializeObject(req, new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy()
},
Formatting = Formatting.Indented
});
request.Content = new StringContent(postJson);
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var response = await httpClient.SendAsync(request);
}
}
}
StickerMessage.cs
public class StickerMessage : IMessage
{
public LineMessageType Type => LineMessageType.sticker;
public string PackageId { get; set; }
public string StickerId { get; set; }
}
ReplyStickerMessageAsync 傳了兩個參數:packageId, stickerId
這個定義在這份文件裡頭,我們在 OnFollow 事件增加回傳貼圖
await lineMessageUtility.ReplyMessageAsync(ev.replyToken, $@"Hi {user.displayName}, 感謝您加入婚禮小助理!");
await lineMessageUtility.ReplyStickerMessageAsync(ev.replyToken, "1", "1");
(X) 結果發現沒作用,原因是 ReplyToken 只能用一次,且也要注意有30秒左右的時效性
ReplyMessageAsync 改接 IMessage 的 List
修改歡迎詞的程式
protected virtual async Task OnFollowAsync(Event ev)
{
// 取得使用者的資訊
var user = await lineProfileUtility.GetUserProfile(ev.source.userId);
// 回傳歡迎詞
var welcome = new TextMessage() { Text = $@"Hi {user.displayName}, 感謝您加入婚禮小助理!" };
var sticker = new StickerMessage() { PackageId = "11539", StickerId = "52114136" };
await lineMessageUtility.ReplyMessageAsync(ev.replyToken, new List<IMessage> {
welcome,
sticker
});
}
實際成果
如何回覆 Line 貼圖
https://developers.line.biz/en/reference/messaging-api/#sticker-message
IList 介面
https://docs.microsoft.com/zh-tw/dotnet/api/system.collections.ilist?view=netcore-3.1
本篇文章同步發佈於我的 Medium 如果這篇文章對你有幫助,就大力追蹤和拍手鼓掌下去吧 !!